
//SEE https://curl.haxx.se/libcurl/c/getinmemory.html

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#include<curl/curl.h>

struct MemoryStruct{
	char *memory;
	size_t size;

};

static size_t 
WriteMemoryBallback(void *contents, size_t size, size_t nmemb, void *userp){
	size_t realsize = size*nmemb;
	struct MemoryStruct *mem = (struct MemoryStruct *) userp;

	mem->memory = realloc(mem->memory, mem->size + realsize + 1);
	if(mem->memory == NULL){
		printf("not enough memory\n");
		return 0;
	}

	memcpy(&(mem->memory[mem->size]), contents, realsize);
	mem->size += realsize;
	mem->memory[mem->size] = 0;

	return realsize;
}

unsigned long get_query(char *search, char *string){

	CURL *curl_handle;
	CURLcode res;

	struct MemoryStruct chunk;

	char query_string[150];
	char *init_query = "https://searx.laquadrature.net/?category_videos=1&pageno=1&language=all&format=rss&q=!yt+%s";

	snprintf(query_string, sizeof(query_string), init_query, search);

	chunk.memory = malloc(1);
	chunk.size = 0;

	curl_global_init(CURL_GLOBAL_ALL);
	
	curl_handle = curl_easy_init();
	curl_easy_setopt(curl_handle, CURLOPT_URL, query_string);
	curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryBallback);
	curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *) &chunk);

	res = curl_easy_perform(curl_handle);
	
	if(res != CURLE_OK)
		fprintf(stderr, "\"curl perform\" failed %s\n", curl_easy_strerror(res));
	else
		printf("%lu bytes retrieved\n", (unsigned long) chunk.size);

	strncpy(string, chunk.memory, sizeof(char[10000]));
	//printf("\nResult Page: \n%s", string);


	curl_easy_cleanup(curl_handle);
	free(chunk.memory);
	curl_global_cleanup();
	
	return chunk.size;
}
